import requests
from utils.json_read import get_params

class MethodToApi:
    def __init__(self):
        pass

    def Get_method(self,json_file,required_desc,required_url,required_params):
        """get方法
        参数：
            json_file:选择存储对应参数的文件
            required_url:输入选择的url
            required_params: 输入选择的参数
        """
        self.url = get_params(json_file, required_desc, 'url_')
        self.all_params = get_params(json_file, '必选参数')
        self.all_params.update(get_params(json_file, '全局参数'))

        #筛选需要的参数
        method_url = {k: v for k, v in self.url.items() if k in required_url}
        url = next(iter(method_url.values()))
        method_params = {k: v for k, v in self.all_params.items() if k in required_params}

        response = requests.get(url=url, params=method_params, timeout=10)
        # 根据Content-Type判断响应格式
        content_type = response.headers.get('Content-Type', '').lower()

        if 'application/json' in content_type or 'text/json' in content_type:
            # JSON格式响应
            return response.json()
        elif 'application/xml' in content_type or 'text/xml' in content_type:
            # XML格式响应
            return response.text
        else:
            # 未知格式，可根据需求处理（这里抛出异常）
            return response.text